package com.tarena.lbs.basic.web.repository.impl;
import com.tarena.lbs.base.protocol.pager.BasePageList;
import com.tarena.lbs.common.basic.converter.UserConverter;
import com.tarena.lbs.common.security.utils.LbsSecurityContenxt;
import com.tarena.lbs.pojo.basic.bo.UserBO;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.basic.web.mapper.UserMapper;
import com.tarena.lbs.basic.web.repository.UserRepository;
import com.tarena.lbs.common.basic.util.RandomUserName;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.pojo.basic.dos.UserDO;
import com.tarena.lbs.pojo.basic.param.UserParam;
import com.tarena.lbs.pojo.basic.query.UserQuery;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Repository;

@Repository
public class UserRepositoryImpl implements UserRepository {

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserConverter userConverter;

    @Override
    public UserBO getDetail(Integer id) {
        UserDO userDO = userMapper.selectUserById(id);
        return userConverter.do2bo(userDO);
    }

    @Override
    public List<Integer> selectTagIdByUserById(int id) {
        return userMapper.selectTagIdByUserId(id);
    }

    @Override
    public BasePageList<UserBO> list(UserQuery query) {
        int page = query.getPageNo();
        int pageSize = query.getPageSize();
        //new PageQuery(page, pageSize);
        List<UserDO> list = userMapper.selectList(query);
        PageInfo<UserDO> pageInfo = new PageInfo<>(list);
        List<UserBO> UserBOList = pageInfo.getList().stream().map(storeDO -> {
            UserBO storeBO = new UserBO();
            BeanUtils.copyProperties(storeDO, storeBO);
            return storeBO;
        }).collect(Collectors.toList());
        return new BasePageList<UserBO>(UserBOList,Long.valueOf(pageInfo.getTotal()));
    }

    @Override
    public Integer saveUserInfo(UserParam userParam) throws Exception {
        //获取登陆用户
        UserPrinciple loginUser = LbsSecurityContenxt.getLoginToken();
        if (loginUser != null) {
            userParam.setId(loginUser.getId());
        }
        UserDO tempUserDO = userMapper.selectUserByPhone(userParam.getPhone());
        if (tempUserDO != null && !tempUserDO.getId().equals(userParam.getId())) {
            throw new BusinessException("10016","用户手机号已存在");
        }
        UserDO userDO = userConverter.param2DO(userParam);
        if (userDO.getId() == null) {
            //生成随机姓名，为了登陆后未修改资料点赞内容
            String name = RandomUserName.createRandomName();
            userDO.setUserName(name);
            userDO.setNickName(name);
            userMapper.insert(userDO);
        } else {
            userMapper.updateByPrimaryKeySelective(userDO);
        }
        return userDO.getId();
    }
}
